package com.k.base.jdk.stream.listmap;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author kivil
 */
public class ListMapTest {
    private static List<Map<String,Object>> list;

    /**
     * select list filter
     * @return list
     */
    private static List<Map<String,Object>> selectList(){
        return list.stream().filter(s -> "2".equals(String.valueOf(s.get("age")))).collect(Collectors.toList());
    }

    /**
     * select count
     * @return count
     */
    private static Long selectCount(){
        return list.stream().filter(s -> "2".equals(String.valueOf(s.get("age")))).count();
    }

    /**
     * select list by page
     * @param pageNo pageNo
     * @param pageSize pageSize
     * @param age searchConditions
     * @return list by page
     */
    private static List<Map<String,Object>> selectListByPage(int pageNo,int pageSize,int age){
        long offset = (long)(pageNo - 1) * pageSize;
        long limit = (long)pageSize;
        return list.stream().filter(s -> Integer.parseInt(String.valueOf(s.get("age")))>=age)
                .skip(offset)
                .limit(limit)
                .collect(Collectors.toList());
    }

    /**
     * Map 转 String
     * @param map map
     * @param kvDelimiter key value delimiter
     * @param itmDelimiter item delimiter
     * @return result
     */
    private static String mapToString(Map<String,String> map, String kvDelimiter, String itmDelimiter){
        return map.entrySet().stream().map(itm->itm.getKey() + kvDelimiter + itm.getValue()).collect(Collectors.joining(itmDelimiter));
    }

    /**
     * Map 转 String 按照 key1=value1&key2=value2 形式
     * @param map map
     * @return result
     */
    private static String mapToString(Map<String,String> map){
        return mapToString(map, "=", "&");
    }

    /**
     * init test data
     */
    private static void initData(){
        list = new ArrayList<>();
        for(int i=0;i<20;i++){
            Map<String,Object> map = new HashMap<>(16);
            map.put("id",i+1);
            map.put("name","tom"+i+1);
            map.put("age",i+1);
            list.add(map);
        }
    }

    /**
     * Main test
     * @param args args
     */
    public static void main(String[] args) {
        initData();
        System.out.println("list:"+list);
        System.out.println("selectList:"+selectList());
        System.out.println("selectCount:"+selectCount());

        List listByPage = selectListByPage(1,10,18);
        List listByPage2 = selectListByPage(2,10,18);
        List listByPage3 = selectListByPage(3,10,18);
        System.out.println("listByPage:"+listByPage +" size:"+listByPage.size());
        System.out.println("listByPage2:"+listByPage2 +" size:"+listByPage2.size());
        System.out.println("listByPage3:"+listByPage3 +" size:"+listByPage3.size());
    }
}
